package com.yoke.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.common.OrderBaseControl;
import com.yoke.service.order.OrderService;
import com.yoke.system.log.SystemLog;
import com.yoke.util.DateUtil;
import jxl.Workbook;
import jxl.write.*;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

/**
 * Created by jiangzeyin on 2017/4/28.
 */
@Controller
@Scope(value = WebApplicationContext.SCOPE_SESSION)
public class ExportControl extends OrderBaseControl {

    @Resource
    OrderService orderService;

    @RequestMapping(value = "exportExcel.html", produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public String exportExcel(String product) {
        String fileName = "订单信息.xls";
        return exportExcel(fileName, product);
    }

    /**
     * @param fileName
     * @param product
     * @return
     * @author jiangzeyin
     * @date 2016-11-16
     */
    private String exportExcel(String fileName, String product) {
        JSONObject jsonOrder = orderService.getProductColumn(userName, product);
        if (jsonOrder == null)
            return "系统提示：Excel文件导出失败：coe=501！";
        JSONArray jsonArray = jsonOrder.getJSONArray("columns");
        if (jsonArray == null || jsonArray.size() <= 0)
            return "系统提示：Excel文件导出失败：coe=502！";
        HashMap<String, String> map = new HashMap<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            map.put(jsonObject.getString("name"), jsonObject.getString("desc"));
        }
        String result = "系统提示：Excel文件导出成功！";
        // 以下开始输出到EXCEL
        try {
            // 定义输出流，以便打开保存对话框______________________begin
            OutputStream os = response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(), "ISO8859-1"));
            // 设定输出文件头
            response.setContentType("application/msexcel");// 定义输出类型
            // 定义输出流，以便打开保存对话框_______________________end

            /** **********创建工作簿************ */
            WritableWorkbook workbook = Workbook.createWorkbook(os);
            /** **********创建工作表************ */
            WritableSheet sheet = workbook.createSheet("订单", 0);
            /** **********设置纵横打印（默认为纵打）、打印纸***************** */
            jxl.SheetSettings sheetset = sheet.getSettings();
            sheetset.setProtected(false);
            /** ***************以下是EXCEL开头大标题，暂时省略********************* */
            // sheet.mergeCells(0, 0, colWidth, 0);
            // sheet.addCell(new Label(0, 0, "XX报表", wcf_center));
            /** ***************以下是EXCEL第一行列标题********************* */
            Collection<String> head = map.values();
            Object[] tiltesCloums = head.toArray();
            for (int i = 0; i < tiltesCloums.length; i++) {
                sheet.addCell(new Label(i, 0, tiltesCloums[i].toString(), wcf_center));
            }
            /** ***************以下是EXCEL正文数据********************* */
            Set<String> keyNames = map.keySet();
            Object[] keyNames_ = keyNames.toArray();
            int i = 1;
            int pageNo = 1;
            while (true) {
                product = convertFilePath(product);
                String jsonStr = orderService.doSelect(userName, product, pageNo + "", 10 + "", null, 0);
                JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                int totalPage = jsonObject1.getIntValue("totalPage");
                JSONArray array = jsonObject1.getJSONArray("results");
                if (array != null) {
                    for (int k = 0; k < array.size(); k++) {
                        JSONObject obj = array.getJSONObject(k);
                        int j = 0;

                        for (Object item : keyNames_) {
                            String string = item.toString();
                            if ("createTime".equals(string)) {
                                sheet.addCell(new Label(j, i, DateUtil.formatTimeStamp(null, obj.getLongValue(string)), wcf_left));
                            } else {
                                sheet.addCell(new Label(j, i, obj.getString(string), wcf_left));
                            }
                            j++;
                        }
                        i++;
                    }
                }
                if (totalPage > pageNo) {
                    pageNo++;
                    continue;
                }
                break;
            }
            /** **********将以上缓存中的内容写到EXCEL文件中******** */
            workbook.write();
            /** *********关闭文件************* */
            workbook.close();
        } catch (Exception e) {
            result = "系统提示：Excel文件导出失败，原因：" + e.toString();
            SystemLog.ERROR().error("生成失败", e);
        }
        return result;
    }

    /**
     * ***********设置单元格字体**************
     */
    private static WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
    private static WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);

    /**
     * ***********以下设置三种单元格样式，灵活备用************
     */
    // 用于标题居中
    private static WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
    // 用于正文居左
    private static WritableCellFormat wcf_left = new WritableCellFormat(NormalFont);
    //private static HashMap<String, String> tableHead = new HashMap<>();
    //private static String tableColumns = "";

    static {
        try {
            wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN);// 线条
            wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
            wcf_center.setAlignment(Alignment.CENTRE); // 文字水平对齐
            wcf_center.setWrap(false); // 文字是否换行

            wcf_left.setBorder(Border.NONE, BorderLineStyle.THIN); // 线条
            wcf_left.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
            wcf_left.setAlignment(Alignment.LEFT); // 文字水平对齐
            wcf_left.setWrap(false); // 文字是否换行
        } catch (WriteException e) {
            // TODO Auto-generated catch block
            SystemLog.ERROR().error("初始化失败", e);
        }
    }
}
